package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatisplusdemo.mapper.PaymentMapper;
import com.example.mybatisplusdemo.model.domain.GoodOrder;
import com.example.mybatisplusdemo.model.domain.PaymentRecord;
import com.example.mybatisplusdemo.model.dto.PaymentRequestDTO;
import com.example.mybatisplusdemo.model.dto.PaymentResponseDTO;
import com.example.mybatisplusdemo.service.IOrderService;
import com.example.mybatisplusdemo.service.IPaymentRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxp
 * @since 2025-07-16
 */
@Service
public class PaymentRecordServiceImpl extends ServiceImpl<PaymentMapper, PaymentRecord> implements IPaymentRecordService {

    @Autowired
    private IOrderService orderService;

    @Override
    @Transactional
    public PaymentResponseDTO createPayment(PaymentRequestDTO paymentRequest) {
        // 1. 验证订单
        GoodOrder order = orderService.getById(paymentRequest.getOrderId());
        if (order == null) {
            return PaymentResponseDTO.fail("订单不存在");
        }

        if (!order.getOrderNo().equals(paymentRequest.getOrderNo())) {
            return PaymentResponseDTO.fail("订单信息不匹配");
        }

        if (order.getStatus() != 0) {
            return PaymentResponseDTO.fail("订单状态不允许支付");
        }

        // 2. 创建支付记录
        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setOrderId(order.getId());
        paymentRecord.setOrderNo(order.getOrderNo());
        paymentRecord.setPaymentNo(generatePaymentNo());
        paymentRecord.setPaymentMethod(paymentRequest.getPaymentMethod());
        paymentRecord.setAmount(paymentRequest.getAmount());
        paymentRecord.setStatus(0); // 未支付
        paymentRecord.setCreateTime(new Date());

        this.save(paymentRecord);

//        PaymentRecord payment = new Payment();
//        payment.setPaymentNo("PAY" + System.currentTimeMillis());
//        payment.setOrder(order);
//        payment.setPaymentMethod(request.getPaymentMethod());
//        payment.setAmount(request.getAmount());
//        payment.setSubject(request.getSubject());
//        payment.setBody(request.getBody());
//        payment.setClientIp(request.getClientIp());
        // 3. 调用第三方支付接口(模拟)

        String payUrl = "https://payment-gateway.com/pay?paymentNo=" + paymentRecord.getPaymentNo();
        switch (paymentRequest.getPaymentMethod()) {
            case 1: // 支付宝
//                payment.setPayUrl("https://mockalipay.com/pay?orderNo=" + order.getOrderNo() +
//                        "&amount=" + paymentRequest.getAmount() + "&paymentNo=" + payment.getPaymentNo());
//                payment.setQrCode("https://mockalipay.com/qr?code=" + RandomUtil.generate(32));
//                break;
                 payUrl = "https://alipay.com/pay?orderNo=" + paymentRecord.getPaymentNo();
                 break;
            case 2: // 微信支付
//                payment.setPayUrl("https://mockwechatpay.com/pay?orderNo=" + order.getOrderNo() +
//                        "&amount=" + request.getAmount() + "&paymentNo=" + payment.getPaymentNo());
//                payment.setQrCode("https://mockwechatpay.com/qr?code=" + RandomUtil.generate(32));
                 payUrl = "https://wechatpay.com/pay?orderNo=" + paymentRecord.getPaymentNo();
                break;
            case 3: // 银行卡
                 payUrl = "https://alipay.com/pay?orderNo=" + paymentRecord.getPaymentNo();

        }

        // 4. 返回支付信息
        PaymentResponseDTO response = new PaymentResponseDTO();
        response.setSuccess(true);
        response.setMessage("支付创建成功");
        response.setPaymentNo(paymentRecord.getPaymentNo());
        response.setPayUrl(payUrl);

        return response;
    }

    @Override
    public PaymentResponseDTO queryPayment(String paymentNo) {
        PaymentRecord paymentRecord = this.lambdaQuery()
                .eq(PaymentRecord::getPaymentNo, paymentNo)
                .one();

        if (paymentRecord == null) {
            return PaymentResponseDTO.fail("支付记录不存在");
        }

        PaymentResponseDTO response = new PaymentResponseDTO();
        response.setSuccess(paymentRecord.getStatus() == 1);
        response.setMessage(getStatusMessage(paymentRecord.getStatus()));
        response.setPaymentNo(paymentRecord.getPaymentNo());

        return response;
    }

    @Override
    @Transactional
    public boolean processPaymentCallback(String paymentNo, String callbackContent) {
        // 1. 查询支付记录
        PaymentRecord paymentRecord = this.lambdaQuery()
                .eq(PaymentRecord::getPaymentNo, paymentNo)
                .one();

        if (paymentRecord == null) {
            return false;
        }

        // 2. 更新支付记录
        paymentRecord.setStatus(1); // 支付成功
        paymentRecord.setPaymentTime(new Date());
        paymentRecord.setCallbackTime(new Date());
        paymentRecord.setCallbackContent(callbackContent);
        paymentRecord.setUpdateTime(new Date());

        this.updateById(paymentRecord);

        // 3. 更新订单状态
        GoodOrder order = new GoodOrder();
        order.setId(paymentRecord.getOrderId());
        order.setStatus(1); // 已支付
        order.setUpdateTime(new Date());

        orderService.updateById(order);

        return true;
    }

    @Override
    @Transactional
    public boolean refund(String paymentNo) {
        // 1. 查询支付记录
        PaymentRecord paymentRecord = this.lambdaQuery()
                .eq(PaymentRecord::getPaymentNo, paymentNo)
                .one();

        if (paymentRecord == null || paymentRecord.getStatus() != 1) {
            return false;
        }

        // 2. 更新支付记录
        paymentRecord.setStatus(3); // 已退款
        paymentRecord.setUpdateTime(new Date());

        this.updateById(paymentRecord);

        // 3. 更新订单状态
        GoodOrder order = new GoodOrder();
        order.setId(paymentRecord.getOrderId());
        order.setStatus(4); // 已退款
        order.setUpdateTime(new Date());

        orderService.updateById(order);

        return true;
    }

    private String generatePaymentNo() {
        return "PAY" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4).toUpperCase();
    }

    private String getStatusMessage(Integer status) {
        switch (status) {
            case 0:
                return "等待支付";
            case 1:
                return "支付成功";
            case 2:
                return "支付失败";
            case 3:
                return "已退款";
            default:
                return "未知状态";
        }
    }
}
